<?php

require_once('database.inc.php');
require_once('track.inc.php');
require_once('ad.inc.php');
require_once('dropdowns.inc.php');
require_once('functions.inc.php');
error_reporting(E_ERROR | E_WARNING | E_PARSE);

#$dbh = connect_db("gene");
$dbm = connect_db();

?>
<html>
<head>
<title>Maptrick - Hall of Cool</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
td.lite {
	background-color: #D0D0D0;
}
td.dark {
	background-color: #A0A0A0;
}

td.old {
	background-color: #808080;
	color: #C0C0C0;
}

td.week2{
	background-color: #B0B0F0;
}

td.week {
	background-color: #A0E0A0;
}

td.day {
	background-color: #FFFFA0;
}

td.hour {
	background-color: #FFD060;
}

td.fifteen {
	background-color: #FF4040;
}

td.dark.ownteam {
	background-color: #900000;
	color: white;
}

td.lite.ownteam {
	background-color: #C00000;
	color: white;
}

td.incup {
	background-color: red;
}

td.maybeincup {
	background-color: #FFFF40;
}

td.notincup {
	background-color: lime;
}

td.unknowncup {
	background-color: #A0A0A0;
}

</style>
</head>
<body>
<?php

if (!$query = mysql_query("
	SELECT zonename
	FROM `leagues_daily`
	WHERE leagueid != 255 
	GROUP BY zonename", $dbm)
) die(mysql_error());

$zonelist = array('any zone');
while ($row = mysql_fetch_array($query)) {
	$zonelist[] = $row[0];
}

$chasetypes = array(
	"0" => "'chased'",
	"1" => "'hosted'",
	"2" => "'chased AND hosted'",
	"3" => "'chased' PLUS 'hosted'"
);

$chasecss = array(
	"0" => "background: #C0C0FF;",
	"1" => "background: #FFFFC0;",
	"2" => "background: #C0FFC0;",
	"3" => "background: salmon;"
);


$ranktypes = array(
	"0" => "coolness",
	"1" => "flags",
	"-1" => "nationality"
);

$home = 0;
if (isset($_GET['hosted']) && $_GET['hosted'] >= 0 && $_GET['hosted'] < count($chasetypes)) $home = $_GET['hosted'];

$altersort = 0;
if (isset($_GET['numflags']) && $_GET['numflags'] > 0) $altersort = 1;
if (isset($_GET['numflags']) && $_GET['numflags'] < 0) $altersort = -1;

$maxnum = 100;
if (isset($_GET['max']) && $_GET['max'] > 0 && is_numeric($_GET['max'])) $maxnum = $_GET['max'];

$start = 0;
if (isset($_GET['start']) && is_numeric($_GET['start']) && $_GET['start'] > 1) {
	$start = $_GET['start'] - 1;
}

$sort = "coolness DESC";
$sort2 = "num DESC";
$sort3 = "activeusers ASC";
if ($altersort > 0) {
	$sort = "num DESC";
	$sort2 = "coolness DESC";
}
if ($altersort < 0) {
	$sort = "activeusers ASC";
	$sort2 = "coolness DESC";
	$sort3 = "num DESC";
}

$leagueid = 0;
$andwhereleague = "";
if (isset($_GET['leagueid']) && $_GET['leagueid'] > 0 && is_numeric($_GET['leagueid'])) {
	$leagueid = $_GET['leagueid'];
	$andwhereleague = "AND l.leagueid = $leagueid";
}

$zoneid = 0;
$andwherezone = "";
if (isset($_GET['zoneid']) && is_numeric($_GET['zoneid']) && $_GET['zoneid'] > 0) {
	$zoneid = $_GET['zoneid'];
	$andwherezone = "AND l.zonename = '{$zonelist[$zoneid]}'";
}

$alliancestable = "";
$andallianceid = "";
$allianceid = 0;
if (isset($_GET['allianceid']) && is_numeric($_GET['allianceid']) && $_GET['allianceid'] > 0) {
	$allianceid = $_GET['allianceid'];
	if ($hit) fedhit($allianceid);
	$alliancestable = ", fed_members a";
	$andallianceid = "AND u.userid = a.userid AND a.allianceid = $allianceid";
}

$federations = getAsocArr("fed_details", "id", "name", $dbm, "LTRIM(name) ASC");
#$numfedmembers = getAsocArr("fed_details", "id", "nummembers", $dbm);
#$numhocmembers = array();
$federationsdropdown = array();

/*
$query = mysql_query("SELECT allianceid, COUNT(*) num FROM fed_members LEFT JOIN flags_updated ON fed_members.userid = flags_updated.userid WHERE flags_updated.userid IS NOT NULL GROUP BY allianceid", $dbm) or die (mysql_error());
while ($row = mysql_fetch_array($query)) {
        $numhocmembers[$row['allianceid']] = $row['num'];
}
*/
if (!$query = mysql_query(
	"SELECT fed_log.allianceid
	FROM fed_details, fed_log
	WHERE fed_log.allianceid = fed_details.id
	AND UNIX_TIMESTAMP(latest) > UNIX_TIMESTAMP() - 7 * 86400
	GROUP BY allianceid ORDER BY LTRIM(name) ASC", $dbm)) die (mysql_error());
while ($row = mysql_fetch_array($query)) {
#	$federationsdropdown[$row['allianceid']] = "{$federations[$row['allianceid']]} ({$numhocmembers[$row['allianceid']]} of {$numfedmembers[$row['allianceid']]})";
	$federationsdropdown[$row['allianceid']] = $federations[$row['allianceid']];
}

?>

<br />
<?php display_ad("hallofcool_top"); ?>
<br />

<form action="hallofcool.php" method="get">
<?php
echo "Show (at most) the <input name=\"max\" size=\"2\" value=\"$maxnum\"> best <a href=\"http://www.hattrick.org/\">Hattrick</a> teams in terms of ";
printgenericdropdown("numflags", $altersort, "", $ranktypes);
echo " ";
printgenericdropdown("hosted", $home, "", $chasetypes, $chasecss); ?>, from: <br />
<?php printzonedropdown($zoneid, $dbm); ?>,  
<?php printleaguedropdown($leagueid, $zoneid, "any country", $dbm); ?>, 
<?php printgenericdropdown("allianceid", $allianceid, "any federation", $federationsdropdown); ?> - 
<input type="submit" value="go!" /><br /><br />
<a href="fedimport.php">(Re-)Add your federation!</a>
</form>

<br />
To add a team to the list, or update a team already entered, simply use the automatic update feature of the <a href="coolness.php#submit">Coolness calculator</a>; use the TeamID field to enter a team other than your own. You can use the "update" link behind any team on this list to fill in its TeamID in the Coolness calculator; don't forget to submit the form after you click "update"!<br /><br />

<?php

$coolness = array();

if (!$query = mysql_query(
	"SELECT SUM(activeusers) active
	FROM leagues_daily
	WHERE leagueid != 255", $dbm)
) die(mysql_error());

$numactive = mysql_result($query, 0);

if (!$query = mysql_query(
	"SELECT u.*, r.*, l.*, UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(FetchedDate) diff
	FROM flags_updated u, flags_ranking r, leagues_daily l $alliancestable
	WHERE u.userid = r.userid
	$andallianceid
	AND l.leagueid = u.leagueid
	$andwherezone
	$andwhereleague
	AND home = $home
	ORDER BY $sort, $sort2, $sort3
	LIMIT $start,$maxnum", $dbm)
) die(mysql_error());

if (mysql_num_rows($query) > 0) { 
	if ($allianceid > 0) {
		$fedlastupdated = getAsocArr("fed_details", "id", "fetched", $dbm);
		echo "You are looking at the Hall of Cool for <b>{$federations[$allianceid]}</b>. The list of members was last updated on <b>{$fedlastupdated[$allianceid]}</b>; if you are a member, you can <a href=\"fedimport.php?allianceid=$allianceid\">update the memberlist here</a>.";
		if (time() - strtotime($fedlastupdated[$allianceid]) > 86400 * 14) echo " <span style=\"background-color: red; color: white\">The last update was <b>OVER 2 WEEKS</b> ago, so it is STRONGLY recommended that you update it now!</span>";
		else if (time() - strtotime($fedlastupdated[$allianceid]) > 86400 * 7) echo " <span style=\"background-color: yellow;\">The last update was over a week ago, so it is recommended that you update it now.</span>";
		echo "<br /><br />\n";
/*		if ($numhocmembers[$allianceid] < $numfedmembers[$allianceid]) {
			$missing = $numfedmembers[$allianceid] - $numhocmembers[$allianceid];
			echo "Currently, the flags of <b>{$numhocmembers[$allianceid]} out of {$numfedmembers[$allianceid]}</b> members have been uploaded; <a href=\"fedimport.php?allianceid=$allianceid#never\">upload the missing $missing members here</a>.";
		} else {
			echo "All members have been uploaded! Get a list of <a href=\"fedimport.php?allianceid=$allianceid#longtime\">teams that have not been updated recently</a>.";
		}*/
	} else {
		echo "<br />\n";
		if (isset($_COOKIE["own_teamid"])) showHocRankBox($_COOKIE["own_teamid"], $dbm);
		echo "<br />\n";
	}
display_ad("hallofcool_mid"); 

echo "<br /><a href=\"hallofcool.php?max=100&numflags=$altersort&hosted=$home&zoneid=$zoneid&leagueid=$leagueid&allianceid=$allianceid\">Start</a> | <a href=\"hallofcool.php?max=100&numflags=$altersort&hosted=$home&zoneid=$zoneid&leagueid=$leagueid&allianceid=$allianceid";
if ($start - 99 > 1) echo "&start=" . ($start - 99);
echo "\">Previous</a> | ";
echo "<a href=\"hallofcool.php?max=100&numflags=$altersort&hosted=$home&zoneid=$zoneid&leagueid=$leagueid&allianceid=$allianceid";
echo "&start=" . ($start + 101);
echo "\">Next</a><br />\n";
?>
<br /><table>
<tr><th>Rank<th>User<th><?php if ($altersort != -1) echo "<a href=\"hallofcool.php?max=$maxnum&numflags=-1&hosted=$home&zoneid=$zoneid&leagueid=$leagueid&allianceid=$allianceid\">Team</a>";
else echo "TEAM"; ?>
<th><?php if ($altersort != 1) echo "<a href=\"hallofcool.php?max=$maxnum&numflags=1&hosted=$home&zoneid=$zoneid&leagueid=$leagueid&allianceid=$allianceid\">Flags</a>";
else echo "FLAGS"; ?>
<th><?php if ($altersort != 0) echo "<a href=\"hallofcool.php?max=$maxnum&numflags=0&hosted=$home&zoneid=$zoneid&leagueid=$leagueid&allianceid=$allianceid\">Coolness</a>"; else echo "COOLNESS"; ?><th>Updated<th>Cup
<?php
	$rank = 1 + $start;
	$prevchigh = "";
	$prevnhigh = "";
	while ($row = mysql_fetch_array($query)) {
		$ago = "";
		$needcomma = 0;

		$oridiff = $row['diff'];
		if ($row['diff'] > 14 * 86400) $class = "lite";
		else if ($row['diff'] > 7 * 86400) $class = "week2";
		else if ($row['diff'] > 86400) $class = "week";
		else if ($row['diff'] > 3600) $class = "day";
		else if ($row['diff'] > 900) $class = "hour";
		else $class = "fifteen";

		if ($row['diff'] >= 7*86400) {
			$ago = floor($row['diff'] / (86400 * 7)) . "w, ";
			$row['diff'] = $row['diff'] % (86400 * 7);
			$needcomma = 1;
		}
		if ($row['diff'] >= 86400) {
			$ago = $ago . floor($row['diff'] / 86400) . "d, ";
			$row['diff'] = $row['diff'] % 86400;
			$needcomma = 1;
		}
		if ($row['diff'] >= 3600) {
			$ago = $ago . sprintf("%02d", floor($row['diff'] / 3600)) . ":";
			$row['diff'] = $row['diff'] % 3600;
			$needcomma = 1;
		} else if ($needcomma) $ago = $ago . "00:";
	
		if ($row['diff'] >= 60) {
			$ago = $ago . sprintf("%02d", floor($row['diff'] / 60)) . ":";
			$row['diff'] = $row['diff'] % 60;
			$needcomma = 1;
		} else if ($needcomma) $ago = $ago . "00:";
	
		if ($row['diff'] > 0) {
			if ($needcomma) $ago = $ago . sprintf("%02d", $row['diff']);
			else $ago = $row['diff'] . "s";
		} else if ($needcomma) $ago = $ago . "00";
	
		if ($row['FetchedDate'] === "1970-01-01 01:00:00") {
			$ago = "too long";
			$class = "old";
		}

		$rowclass = "";
		$ranktext = "";

		if ($prevnhigh != $row['num'] || $prevchigh != $row['coolness']) {
			$ranktext = $rank;
		}
		$prevnhigh = $row['num'];
		$prevchigh = $row['coolness'];

		if (isset($_COOKIE["own_teamid"]) && $_COOKIE["own_teamid"] == $row['TeamID']) $rowclass = " ownteam";
		echo "\t<a name=\"team{$row['TeamID']}\" /><tr><td class=\"dark$rowclass\" align=\"center\">$ranktext<td class=\"lite$rowclass\">{$row['LoginName']}";
		if ($row['HasSupporter'] == 1) echo ' <img src="micro_star.gif">';
		echo "<td class=\"dark$rowclass\"><a href=\"hallofcool.php?max=$maxnum&leagueid={$row['LeagueID']}&hosted=$home&numflags=$altersort&allianceid=$allianceid\"><img src=\"flags/{$row['LeagueID']}flag.gif\" border=\"1\"/></a> {$row['TeamName']}<td class=\"lite$rowclass\" align=\"right\">{$row['num']}<td class=\"dark$rowclass\" align=\"right\">{$row['coolness']}<td class=\"$class\" align=\"right\"><font size=\"1\">$ago ago</font> (<a href=\"coolness.php?tid={$row['TeamID']}\">watch</a> | <a href=\"coolness.php?tid={$row['TeamID']}#submit\">update</a>)";
		switch ($row['StillInCup']) {
			case -1:	echo "<td class=\"unknowncup\">?\n";break;
			case 0: 	echo "<td class=\"notincup\">no\n";break;
			case 1: 	if ($oridiff >= 7*86400 ) {
						echo "<td class=\"maybeincup\">yes?\n";
					} else {
						echo "<td class=\"incup\">yes\n";
					}
					break;
			default: echo "<td>!\n"; 
		}
		$rank++;
	}
	echo "</table>";
	echo "<a href=\"hallofcool.php?max=100&numflags=$altersort&hosted=$home&zoneid=$zoneid&leagueid=$leagueid&allianceid=$allianceid";
	if ($start - 99 > 1) echo "&start=" . ($start - 99);
	echo "\">Previous</a> | ";
	echo "<a href=\"hallofcool.php?max=100&numflags=$altersort&hosted=$home&zoneid=$zoneid&leagueid=$leagueid&allianceid=$allianceid";
	echo "&start=" . ($start + 101);
	echo "\">Next</a><br />\n";
	if ($allianceid > 0) {
		$fedlogourls = getAsocArr("fed_details", "id", "logourl", $dbm);
		if ($fedlogourls[$allianceid] != '') echo "<br /><img src=\"{$fedlogourls[$allianceid]}\"><br /><br />";
	}
} else if ($allianceid > 0) {
	echo "<b>No teams from Federation $allianceid qualify for the Hall of Cool in your current selection</b>. Perhaps you would like to <a href=\"fedimport.php\">update it</a> or <a href=\"fedimport.php?allianceid=$allianceid#never\">upload some members</a>?<br />\n";
} else {
	echo "<b>No teams in your current selection qualified for the Hall of Cool</b>. Please try another category!<br />\n";
}
?>
<br />
If you're interested, there are stats about <a href="coolstats.php">country representation in the Hall of Cool</a>.<br /><br />
<?php

display_ad("hallofcool_bottom"); urchin();?>
<br />
</body>
</html>
